import {
  useState,
  useEffect,
  forwardRef,
  useImperativeHandle,
  useCallback,
} from 'react';
import {
  Table,
  Alert,
  Tooltip,
  Dropdown,
  Menu,
  Checkbox,
  Popover,
  Radio,
  message,
} from 'antd';
import type {
  TableProps,
  TableColumnType,
  TablePaginationConfig,
  CheckboxOptionType,
} from 'antd';
import {
  SyncOutlined,
  ColumnHeightOutlined,
  SettingOutlined,
} from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import ColumnSetting from './ColumnSetting.tsx';
import './index.less';
import { log } from 'console';

interface STableProps<T> extends TableProps<T> {
  data: (params: any) => Promise<any>;
  pageNum?: number;
  size?: number;
  showSizeChanger?: boolean;
  compSize?: 'small' | 'middle' | 'large';
  alert?: boolean | { show: boolean; clear?: () => void };
  lineSelection?: boolean;
  showPagination?: boolean | 'auto';
  defaultPageSize?: number;
  pageSizeOptions?: string[];
  extraTool?: any[];
  toolConfig?: {
    refresh?: boolean;
    height?: boolean;
    columnSetting?: boolean;
    striped?: boolean;
  };
  operator?: React.ReactNode;
}

const STable = forwardRef(
  <T extends object>(props: STableProps<T>, ref: any) => {
    const { t } = useTranslation();
    const [loading, setLoading] = useState(false);
    const [dataSource, setDataSource] = useState<T[]>([]);
    const [pagination, setPagination] = useState<TablePaginationConfig>({});
    const [columnsSetting, setColumnsSetting] = useState(props.columns || []);
    const [customSize, setCustomSize] = useState(props.compSize || 'middle');
    const [rowClassNameSwitch, setRowClassNameSwitch] = useState(false);
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [selectedRows, setSelectedRows] = useState<T[]>([]);

    // 暴露外部方法
    useImperativeHandle(ref, () => ({
      refresh: (resetToFirstPage = false) => {
        if (resetToFirstPage) {
          setPagination((prev) => ({ ...prev, current: 1 }));
        }
        loadData();
      },
    }));

    // 加载数据
    const loadData = useCallback(
      async (
        pagination?: TablePaginationConfig,
        filters?: Record<string, any>,
        sorter?: any,
      ) => {
        setLoading(true);
        try {
          const params = {
            pageNum: pagination?.current || props.pageNum || 1,
            pageSize: pagination?.pageSize || props.size || 10,
            ...filters,
            ...(sorter?.field && { sortField: sorter.field }),
            ...(sorter?.order && { sortOrder: sorter.order }),
          };

          console.log('params', params);

          const { result } = await props.data(params);
          const { rows, total, current, pageSize } = result;

          setDataSource(rows || []);
          setPagination({
            ...pagination,
            total,
            current,
            pageSize,
            showSizeChanger: props.showSizeChanger,
            pageSizeOptions: props.pageSizeOptions,
            showTotal: (total) => `${t('total')} ${total} ${t('items')}`,
          });
        } catch (error) {
          message.error(t('loadFailed'));
        } finally {
          setLoading(false);
        }
      },
      [
        props.data,
        props.pageNum,
        props.size,
        props.showSizeChanger,
        props.pageSizeOptions,
        t,
      ],
    );

    // 初始化加载
    useEffect(() => {
      loadData();
    }, [loadData]);

    // 处理行选择
    const handleRowSelectionChange = (
      selectedKeys: React.Key[],
      selectedRows: T[],
    ) => {
      setSelectedRowKeys(selectedKeys);
      setSelectedRows(selectedRows);
    };

    // 渲染工具栏
    const renderToolbar = () => {
      const { toolConfig, operator } = props;
      const tools = [];

      // 刷新按钮
      if (toolConfig?.refresh) {
        tools.push(
          <Tooltip key="refresh" title={t('refresh')}>
            <SyncOutlined onClick={() => loadData()} />
          </Tooltip>,
        );
      }

      // 密度调整
      if (toolConfig?.height) {
        const menu = (
          <Menu
            selectedKeys={[customSize]}
            onClick={({ key }) => setCustomSize(key as any)}
          >
            <Menu.Item key="default">{t('default')}</Menu.Item>
            <Menu.Item key="middle">{t('medium')}</Menu.Item>
            <Menu.Item key="small">{t('compact')}</Menu.Item>
          </Menu>
        );

        tools.push(
          <Dropdown key="density" overlay={menu} trigger={['click']}>
            <Tooltip title={t('density')}>
              <ColumnHeightOutlined />
            </Tooltip>
          </Dropdown>,
        );
      }

      // 列设置
      if (toolConfig?.columnSetting) {
        tools.push(
          <Popover
            key="columnSetting"
            trigger="click"
            content={
              <ColumnSetting
                columns={columnsSetting}
                onChange={setColumnsSetting}
              />
            }
          >
            <Tooltip title={t('columnSettings')}>
              <SettingOutlined />
            </Tooltip>
          </Popover>,
        );
      }

      return (
        <div className="s-table-tool">
          <div className="s-table-tool-left">{operator}</div>
          <div className="s-table-tool-right">
            {toolConfig?.striped && (
              <Checkbox
                checked={rowClassNameSwitch}
                onChange={(e) => setRowClassNameSwitch(e.target.checked)}
              >
                {t('zebraStriping')}
              </Checkbox>
            )}
            {tools}
          </div>
        </div>
      );
    };

    // 渲染警告信息
    const renderAlert = () => {
      if (!props.alert) return null;

      return (
        <Alert
          message={
            <>
              <span>
                {t('selectedItems', { count: selectedRowKeys.length })}
              </span>
              <a
                onClick={() => {
                  setSelectedRowKeys([]);
                  setSelectedRows([]);
                }}
              >
                {t('clear')}
              </a>
            </>
          }
          type="info"
          showIcon
          className="mb-4"
        />
      );
    };

    // 处理行样式
    const rowClassName = (record: T, index: number) => {
      if (rowClassNameSwitch && index % 2 === 1) {
        return 'table-striped';
      }
      return props.rowClassName?.(record, index) || '';
    };

    return (
      <div className="table-wrapper">
        {renderToolbar()}
        {renderAlert()}
        <Table
          {...props}
          loading={loading}
          dataSource={dataSource}
          columns={columnsSetting.filter((col) => !col.hidden)}
          pagination={props.showPagination ? pagination : false}
          rowClassName={rowClassName}
          rowSelection={
            props.rowSelection
              ? {
                  ...props.rowSelection,
                  selectedRowKeys,
                  onChange: handleRowSelectionChange,
                }
              : undefined
          }
          size={customSize}
          onChange={(pagination, filters, sorter) => {
            loadData(pagination, filters, sorter);
          }}
        />
      </div>
    );
  },
);

export default STable;
